﻿using Inovout.Cloud.Applications.Security.Models;
using Inovout.Services;
using NHibernate.Criterion;
using System;

namespace Inovout.Cloud.Applications.Security.Services
{
    public class WebApplicationCredentialService :  RepositoryService<WebApplicationCredential>, IWebApplicationCredentialService
    {
        public WebApplicationCredential FindByClientId(string clientId)
        {
            return base.Repository.Find(Restrictions.Eq("ClientId", clientId));
        }

        public override void Save(WebApplicationCredential webApplicationCredential)
        {
            string clientId = Guid.NewGuid().ToString("N");
            string clientSecret = Guid.NewGuid().ToString("N");
            webApplicationCredential.ClientId = clientId;
            webApplicationCredential.ClientSecret = clientSecret;
            webApplicationCredential.ApplicationUser.Credentials.Add(webApplicationCredential);
            base.Save(webApplicationCredential);
        }

        public override void Delete(object id)
        {
            WebApplicationCredential webApplicationCredential = base.FindById(id);
            webApplicationCredential.ApplicationUser.Credentials.Remove(webApplicationCredential);
            base.Delete(id);
        }

        public void UpdateClientSecret(WebApplicationCredential webApplicationCredential)
        {
            string clientSecret = Guid.NewGuid().ToString("N");
            webApplicationCredential.ClientSecret = clientSecret;  
            webApplicationCredential.ApplicationUser.Credentials.Add(webApplicationCredential);
            base.Save(webApplicationCredential);
        }   
    }


}
